#include "DataOutStream.h"

DataOutStream::DataOutStream()
{
	mPos = 0;
	mFileName = "";

}

DataOutStream::~DataOutStream()
{
	Clear();
}

void DataOutStream::SetFileName(const String& fileName)
{
	mFileName = fileName;
}

String DataOutStream::GetFileName()
{
	return mFileName;
}

void DataOutStream::Clear()
{
	mPos = 0;
	mData.clear();
}

bool DataOutStream::Save(Buffer& buffer)
{
	if (!buffer.Resize(mPos))
	{
		Error::Instance().SetMessage("Unable to save \"" + mFileName + "\", buffer resize failed!");
		return false;
	}

	std::memcpy(buffer.GetData(), &mData[0], mPos);

	return true;
}

s32 DataOutStream::GetPosition() const
{
	return mPos;
}

void DataOutStream::Write(const c8* buffer, u32 num)
{
	if (num <= 0) return;

	mData.resize(mData.size() + num, 0);

	std::memcpy(&mData[mPos], buffer, num);
	mPos += num;
}

void DataOutStream::WriteChar(c8 Char)
{
	Write(reinterpret_cast<c8*>(&Char), sizeof(c8));
}

void DataOutStream::WriteInt(s32 Int)
{
	Write(reinterpret_cast<c8*>(&Int), sizeof(s32));
}

void DataOutStream::WriteFloat(f32 Float)
{
	Write(reinterpret_cast<c8*>(&Float), sizeof(f32));
}

void DataOutStream::WriteByte(u8 Byte)
{
	Write(reinterpret_cast<c8*>(&Byte), sizeof(u8));
}

void DataOutStream::WriteWord(u16 Word)
{
	Write(reinterpret_cast<c8*>(&Word), sizeof(u16));
}

void DataOutStream::WriteDWord(u32 DWord)
{
	Write(reinterpret_cast<c8*>(&DWord), sizeof(u32));
}

void DataOutStream::WriteString(const String& string, u32 size)
{
	std::vector<c8> buffer;

	buffer.resize(size + 1, 0);
	buffer[size] = '\0';

	std::memcpy(&buffer[0], string.c_str(), std::min(size, (u32)string.size()));
	buffer[string.size()] = '\0';

	Write(&buffer[0], size);
}
